//
//  UIColor+Extension.swift
//  qfxmerchant
//
//  Created by QFX on 2023/3/1.
//  Copyright © 2023 Zhengyuan wan. All rights reserved.
//

import Foundation
import UIKit

public extension UIColor {
    
    public var toHexString: String {
        var r: CGFloat = 0
        var g: CGFloat = 0
        var b: CGFloat = 0
        var a: CGFloat = 0
        
        self.getRed(&r, green: &g, blue: &b, alpha: &a)
        
        return String(
            format: "%02X%02X%02X",
            Int(r * 0xff),
            Int(g * 0xff),
            Int(b * 0xff)
        )
    }
    
    public convenience init?(hexString: String) {
        
        self.init(hex: hexString, alpha: 1)
    }
    
    public convenience init?(hex: String) {
        
        self.init(hex: hex, alpha: 1)
    }
    
    public convenience init?(hex: String , alpha :CGFloat) {
        
        var tmpHex = hex
        if hex.hasPrefix("#"){
            
            let startIndex = hex.index(of: "#") ?? hex.startIndex
            let index = hex.index(startIndex, offsetBy: 1)//往后移动一位
            let text = hex[index ..< hex.endIndex]
//            DPrint("text: \(text)")
            tmpHex = String(text)
            
        }
        
        let scanner = Scanner(string: tmpHex)
        scanner.scanLocation = 0
        
        var rgbValue: UInt64 = 0
        
        scanner.scanHexInt64(&rgbValue)
        
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        
        self.init(
            red: CGFloat(r) / 0xff,
            green: CGFloat(g) / 0xff,
            blue: CGFloat(b) / 0xff,
            alpha: alpha
        )
        
    }
}
